package au.com.evoCoach.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class BaseDAO extends HibernateDaoSupport {

	private Class classType;
	
	public BaseDAO(Class classType) {
		this.classType = classType;
	}
	
	public Object findById(int id) {
		return getHibernateTemplate().get(classType, id);
	}
	
	@SuppressWarnings("unchecked")
	public List findAll() {
        DetachedCriteria criteria = getCriteria();

        return getHibernateTemplate().findByCriteria(criteria);
    }

	protected DetachedCriteria getCriteria() {
		return DetachedCriteria.forClass(classType);
	}
	
	public Serializable save(Object object) {
		if (object.getClass().getName().startsWith(classType.getName())) {
			return getHibernateTemplate().save(object);
		}
		
		throw new IllegalArgumentException("expect object of type " + classType);
	}
	
	public void update(Object object) {
		if (object.getClass().getName().startsWith(classType.getName())) {
			getHibernateTemplate().update(object);
		}
		else {
			throw new IllegalArgumentException("expect object of type " + classType);
		}
	}
	
	public void delete(Object object) {
		if (object.getClass().getName().startsWith(classType.getName())) {
			getHibernateTemplate().delete(object);
		}
		else {
			throw new IllegalArgumentException("expect object of type " + classType);
		}
	}
	
}
